import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { vueInstance } from '@/main'
import { debounce } from 'throttle-debounce'
import { isArrayBuffer } from 'lodash'

// 报错防抖处理
const errorDebounce = debounce(300, (message) => {
  vueInstance.$message.warning(message)
})

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      method: 'post',
      headers: {
        // userToken: store.state.user.userToken
      }
    }
    return config
  }

  interceptors (instance) {
    // 请求拦截Spin.hide()
    instance.interceptors.request.use(
      (config) => {
        // const token = store.getters['user/getSID']
        // if (token) {
        //   config.url = `${config.url}?SID=${token}`
        // }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      (res) => {
        const data = res.data
        const { code, errorMsg } = data
        const needPostMessageList = ['NOT_AUTH', 'TIME_OUT', 'NOT_REGISTERED', 'EXPIRED']
        if (code === 'OK') {
          return data
        } else if (code === 'NOT_LOGIN' || code === 'OTHER_LOGIN') {
          store.commit('user/setUserInfo', {})
          router.replace({ name: 'home' })
          errorDebounce(errorMsg)
          return Promise.reject(data)
        } else if (code === 'FIELD_ERROR') {
          for (const key in errorMsg) {
            vueInstance.$message.error(`${errorMsg[key]}`)
          }
          return Promise.reject(data)
        } else if (needPostMessageList.includes(code)) {
          errorDebounce(errorMsg)
          return Promise.reject(data)
        } else if (isArrayBuffer(data)) {
          return res
        } else if (data instanceof Blob) {
          return res
        } else {
          vueInstance.$message.error(errorMsg)
          return Promise.reject(data)
        }
      },
      (error) => {
        return Promise.reject(error)
      }
    )
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
